<template>
<!--批量新增商品-->
<div>
    <div style="margin-bottom: -25px;">
        <el-link type="primary" @click="lookUploatdHistory">查看上传历史</el-link>
    </div>
    <el-form :model="dataForm" label-width="120px" :rules="dataFormRules" ref="dataForm" :size="size">
        <el-row class="searchDialog-input mt30">
            <el-form-item label="商品类型:" prop="type" style="width: 20%">
                <el-select v-model="dataForm.type" placeholder="请选择商品类型" style="width: 100%">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品形式:" prop="typeOfProduct" style="width: 20%">
                <el-select v-model="dataForm.typeOfProduct" placeholder="请选择商品形式" style="width: 100%">
                    <el-option v-for="item in typeOfProductOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品类目:" prop="categoryId" style="width: 20%">
                <el-form-item>
                    <tree-select :options="categoryOptions" placeholder="请选择商品类目" :disable-branch-nodes="true" v-model="dataForm.categoryId" @select="treeSelect" :normalizer="normalizer" />
                </el-form-item>
            </el-form-item>
            <el-form-item label="选择导入文件：" class="chooseImportDocument">
                <el-input v-model="dataForm.fileName" disabled auto-complete="off"></el-input>
                <div class="" style="margin-left: 280px;margin-top: -32px;">
                    <el-upload class="upload-demo" ref="upload" :on-exceed="handleExceed" :action="uploadExcel()" :on-success="handleSuccess" :on-error="handlerror" name="file" :on-change="showFileName" :before-upload="beforeUpload" :file-list="fileList" :show-file-list="false" :auto-upload="false">
                        <el-button slot="trigger" @click="flag=true" size="small" type="primary" style="display:inline-block">选取文件</el-button>
                        <el-button size="small" type="success" @click="submitUpload" style="display:inline-block">批量导入</el-button>
                    </el-upload>
                </div>
            </el-form-item>
            <el-form-item style="width: 40%">
                <el-link type="primary" @click="donwloadExcel">生成模板并下载</el-link>
                <span>（提示：下载模板时请先选择商品类型、商品形式、商品类目）</span>
            </el-form-item>
        </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click="goBack">返回</el-button>
    </div>
</div>
</template>

<script>
import CyTable from "@/views/Core/CyTable";
import KtButton from "@/views/Core/KtButton";
import {
    format,
    formatDate
} from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import axios from "axios";

export default {
    components: {
        KtButton,
        CyTable,
        TableColumnFilterDialog,
        TreeSelect
    },
    data() {
        return {
            deptId: localStorage.getItem("deptId"),
            localFile: {},
            flag: false,
            typeOptions: [{
                    value: "1",
                    label: "常规商品"
                },
                {
                    value: "3",
                    label: "海购商品"
                },
                {
                    value: "31",
                    label: "称重商品"
                }
            ],
            typeOfProductOptions: [{
                    value: "1",
                    label: "普通商品"
                },
                {
                    value: "2",
                    label: "系列子品"
                }
            ],
            categoryOptions: [],
            categoryName: "",
            size: "small",
            dataForm: {
                type: "",
                typeOfProduct: "",
                categoryId: null,
                fileName: ""
            },
            dataFormRules: {
                type: [{
                    required: true,
                    message: "请选择商品类型",
                    trigger: "change"
                }],
                typeOfProduct: [{
                    required: true,
                    message: "请选择商品形式",
                    trigger: "change"
                }],
                categoryId: [{
                    required: true,
                    message: "请选择商品类目",
                    trigger: "change"
                }]
            },
            fileList: [],
            size: "small"
        };
    },
    mounted() {
        this.queryCategory();
    },
    methods: {
        lookUploatdHistory: function () {
            this.$router.push({
                path: "/ProductUploadHistory"
            });
        },
        //本地文件回显
        showFileName(event) {
            if (this.flag) {
                this.dataForm.fileName = event.name;
            }
        },
        //类目树选中
        treeSelect: function (param) {
            this.categoryName = param.name;
        },
        //返回文件名
        returnExcelName: function () {
            let excelName = "";
            let type = "";
            let typeOfProduct = "";
            if (this.dataForm.type == 1) {
                type = "常规商品";
            } else if (this.dataForm.type == 3) {
                type = "海购商品";
            } else {
                type = "称重商品";
            }
            if (this.dataForm.typeOfProduct == 1) {
                typeOfProduct = "普通商品";
            } else {
                typeOfProduct = "系列子品";
            }
            let date =
                new Date().getFullYear().toString() +
                (new Date().getMonth() + 1).toString() +
                new Date().getDate().toString();
            excelName =
                type +
                "-" +
                typeOfProduct +
                "-" +
                this.categoryName +
                "-" +
                date +
                ".xls";
            return excelName;
        },
        //提交文件
        submitUpload: function (file) {
            if (this.dataForm.fileName == "") {
                return this.$message({
                    message: "请选择文件",
                    type: "error"
                });
            }
            if (this.dataForm.categoryId == "") {
                return this.$message({
                    message: "请选择商品类目",
                    type: "error"
                });
            }
            if (this.dataForm.type == "") {
                return this.$message({
                    message: "请选择商品类型",
                    type: "error"
                });
            }
            if (this.dataForm.typeOfProduct == "") {
                return this.$message({
                    message: "请选择商品形式",
                    type: "error"
                });
            }
            this.$refs.upload.submit();
        },
        //上传校验
        beforeUpload(file) {
            //.xls,.xlsx
            const isJPG =
                file.type === "application/vnd.ms-excel" ||
                file.type ===
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            if (!isJPG) {
                this.$message.error("上传文件只能是.xls,.xlsx格式!");
                this.dataForm.fileName = "";
                return isJPG;
            }
        },
        //文件上传数量限制
        handleExceed: function () {
            this.$alert("最多上传一个", "警告", {
                confirmButtonText: "确定"
            });
        },
        //生成模板并且下载
        donwloadExcel: function () {
            let this_ = this;
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    axios({
                            method: "post",
                            url: "http://localhost:8087/jic-product/productExcel/batchUploadProductTemplate",
                            data: this.dataForm,
                            responseType: "blob"
                        })
                        .then(res => {
                            console.log(res);
                            const link = document.createElement("a");
                            let blob = new Blob([res.data], {
                                type: "application/vnd.ms-excel"
                            });
                            link.style.display = "none";
                            link.href = URL.createObjectURL(blob);
                            let excelName = this_.returnExcelName();
                            link.setAttribute("download", excelName);
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        })
                        .catch(error => {});
                }
            });
        },
        //查询商品类目
        queryCategory: function () {
            let this_ = this;
            let params = {};
            this_.categoryOptions = [];
            this.utils.request.queryBehindCategory(params, function (data) {
                if (data.data != null) {
                    this_.categoryOptions = data.data;
                }
            });
        },
        //格式化商品类目查询条件
        normalizer(node) {
            if (node.categoryList == null || node.categoryList.length == 0) {
                delete node.categoryList;
            }
            return {
                id: node.id,
                label: node.name,
                children: node.categoryList
            };
        },
        //上传成功
        handleSuccess: function (res) {
            if (res.code == "0000") {
                this.$message({
                    message: "操作成功",
                    type: "success"
                });
                this.dataForm = {
                    type: "",
                    typeOfProduct: "",
                    categoryId: null,
                    fileName: ""
                };
                this.$nextTick(() => {
                    this.$refs["dataForm"].clearValidate();
                });
                this.flag = false;
            }
        },
        //上传失败
        handlerror: function (res) {
            this.$message({
                message: "上传错误，请重试",
                type: "error"
            });
            this.dataForm = {
                type: "",
                typeOfProduct: "",
                categoryId: null,
                fileName: ""
            };

            this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
            });
            this.flag = false;
        },
        //上传文件
        uploadExcel() {
            return (
                "http://localhost:8087/jic-product/productExcel/batchUploadProduct" +
                "?categoryId=" +
                this.dataForm.categoryId +
                "&typeOfProduct=" +
                this.dataForm.typeOfProduct +
                "&type=" +
                this.dataForm.type + "&deptId=" + this.deptId
            );
        },
        //返回商品列表
        goBack: function () {
            this.$router.push({
                path: "pages/product/productManagement"
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.chooseImportDocument {
    /deep/ .el-input {
        width: 260px !important;
    }
}

.mt30 {
    margin-top: 30px;
}
</style>
